package com.mhl.campuscabinet;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.mhl.adapter.SellImageAdapter;
import com.mhl.client.OkHttpUtils;
import com.mhl.client.QiNiuUtil;
import com.mhl.entity.LocalData;
import com.mhl.entity.Tag;
import com.mhl.entity.User;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SellFragment extends Fragment implements View.OnClickListener {

    // 动作码
    public static final int TAKE_PHOTO = 1;
    public static final int CHOOSE_PHOTO = 2;
    // View
    private RecyclerView recyclerView;
    private List<Bitmap> silist;
    private SellImageAdapter sellImageAdapter;
    private CheckBox checkBox1, checkBox2, checkBox3, checkBox4,checkBox5, checkBox6, checkBox7, checkBox8;
    private List<CheckBox> checkBoxList = new ArrayList<CheckBox>();

    private ArrayList<Tag> TagList = LocalData.getInstance().TagList;

    private Button uploadphotos,sellproduct;
    private EditText sellname,sellprice,selldescribe;
    private SelectPicPopupWindow menuWindow;


    private ArrayList<String> tags = new ArrayList<>();
    private ArrayList<Integer> tagsInt = new ArrayList<>();
    private ArrayList<String> urls = new ArrayList<>();


    // 图片Uri
    private Uri imageUri;
    // 工具
    private QiNiuUtil qiNiuUtil = QiNiuUtil.getInstance();
    // Handler
    Handler handler;

    // 构造方法
    public SellFragment() {

    }

    public SellFragment(Handler handler) {
        this.handler = handler;
    }

    @Override
    public void onStart() {
        super.onStart();
        System.out.println("上架界面开始");
    }

    @Override
    public void onResume() {
        super.onResume();
        // TODO 清空所有操作
        System.out.println("上架界面继续");
    }

    @Override
    public void onPause() {
        super.onPause();
        System.out.println("上架界面暂停");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        System.out.println("上架界面毁灭");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_sell, container, false);
        initview(view);
        recyclerView = (RecyclerView)view.findViewById(R.id.list_sellimage);
//        StaggeredGridLayoutManager layoutManager = new
//                StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
//        // 解决重新分配高度的问题
//        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        GridLayoutManager layoutManager = new GridLayoutManager (getContext(),3);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        silist = new ArrayList<>();

        sellImageAdapter = new SellImageAdapter(silist);
        recyclerView.setAdapter(sellImageAdapter);

        // Inflate the layout for this fragment
        return view;
    }

    public void initview(View view){
        uploadphotos = view.findViewById(R.id.uploadphotos);
        sellproduct = view.findViewById(R.id.sellproduct);
        sellname = view.findViewById(R.id.sell_name);
        sellprice = view.findViewById(R.id.sell_price);
        selldescribe = view.findViewById(R.id.sell_describe);
        checkBox1 = (CheckBox) view.findViewById(R.id.sellBox1);
        checkBox2 = (CheckBox) view.findViewById(R.id.sellBox2);
        checkBox3 = (CheckBox) view.findViewById(R.id.sellBox3);
        checkBox4 = (CheckBox) view.findViewById(R.id.sellBox4);
        checkBox5 = (CheckBox) view.findViewById(R.id.sellBox5);
        checkBox6 = (CheckBox) view.findViewById(R.id.sellBox6);
        checkBox7 = (CheckBox) view.findViewById(R.id.sellBox7);
        checkBox8 = (CheckBox) view.findViewById(R.id.sellBox8);

        checkBoxList.add(checkBox1);
        checkBoxList.add(checkBox2);
        checkBoxList.add(checkBox3);
        checkBoxList.add(checkBox4);
        checkBoxList.add(checkBox5);
        checkBoxList.add(checkBox6);
        checkBoxList.add(checkBox7);
        checkBoxList.add(checkBox8);

        uploadphotos.setOnClickListener(this);
        sellproduct.setOnClickListener(this);


        if(TagList.size() < 8){
            for (int i = 0; i < TagList.size(); i++) {
                checkBoxList.get(i).setText(TagList.get(i).getName());
                System.out.println(TagList.get(i).getName());
            }
        }
        else{
            for (int i = 0; i < checkBoxList.size(); i++) {
                checkBoxList.get(i).setText(TagList.get(i).getName());
                System.out.println(TagList.get(i).getName());
            }
        }
    }

    public void take_photo(){
        // 创建File对象存储拍照照片
        File outputImage = new File(getActivity().getExternalCacheDir(), "output_image.jpg");
        try {
            if(outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        imageUri = FileProvider.getUriForFile(getActivity(),
                "com.mhl.campuscabinet.fileprovider", outputImage);
        // 启动相机程序
        // 动态申请打开相机的权限
        int cameraPermissionCheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA);
        int readPermissionCheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE);
        int writePermissionCheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (cameraPermissionCheck != PackageManager.PERMISSION_GRANTED
                || readPermissionCheck != PackageManager.PERMISSION_GRANTED
                || writePermissionCheck != PackageManager.PERMISSION_GRANTED) {
            String[] permissions = new String[]{Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE};
            ActivityCompat.requestPermissions(
                    getActivity(),
                    permissions,
                    0);
        } else {
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(intent, TAKE_PHOTO);
        }
    }

    public void choose_photo(){
        // 动态申请打开图库的权限
        if(ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE
                    }, 1);
        } else {
            openAlbum();
        }
    }

    // 动态申请权限的回调函数
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull @NotNull String[] permissions,
                                           @NonNull @NotNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 0:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    startActivityForResult(intent, TAKE_PHOTO);
                } else {
                    Toast.makeText(getActivity(), "You denied the permission",
                            Toast.LENGTH_SHORT).show();
                }
                break;
            case 1:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum();
                } else {
                    Toast.makeText(getActivity(), "You denied the permission",
                            Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    // 处理通过摄像或从图库中选择的照片
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                if(resultCode==getActivity().RESULT_OK) {
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(imageUri));
                        //picture.setImageBitmap(bitmap);
                        silist.add(bitmap);
                        sellImageAdapter.notifyDataSetChanged();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                String temp = "http://cc.edenlia.icu/";
                                temp += qiNiuUtil.uploadToQiNiu(bitmap, null);
                                urls.add(temp);
                                System.out.println("now url is: "+temp);
                            }
                        }).start();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case CHOOSE_PHOTO:
                if(resultCode==getActivity().RESULT_OK) {
                    handleImageOnKitKat(data);
                }
            default:
                break;
        }
    }

    // 打开图库
    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO);
    }

    // 从封装Uri提取真实Uri
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if(DocumentsContract.isDocumentUri(getActivity(), uri)) {
            String docId = DocumentsContract.getDocumentId(uri);
            if("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                        , selection);
            } else if("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content:" +
                        "//downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if("content".equalsIgnoreCase(uri.getScheme())) {
            imagePath = getImagePath(uri, null);
        } else if("file".equalsIgnoreCase(uri.getScheme())) {
            imagePath = uri.getPath();
        }
        displayImage(imagePath);
        String finalImagePath = imagePath;
        new Thread(new Runnable() {
            @Override
            public void run() {
                String temp = "http://cc.edenlia.icu/";
                temp += qiNiuUtil.uploadToQiNiu(BitmapFactory.decodeFile(finalImagePath), null);
                urls.add(temp);
            }
        }).start();
    }

    // 根据Uri获取图片路径
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getActivity().getContentResolver().query(uri, null, selection,
                null, null, null);
        if(cursor != null) {
            if(cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore
                        .Images.Media.DATA));
                cursor.close();
            }
        }
        return path;
    }

    // 根据图片路径显示图片
    private void displayImage(String imagePath) {
        if(imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            //picture.setImageBitmap(bitmap);
            silist.add(bitmap);
            sellImageAdapter.notifyDataSetChanged();
        } else {
            Toast.makeText(getActivity(), "failed to get image", Toast.LENGTH_SHORT).show();
        }
    }


    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.uploadphotos://上传照片
                selectImgs();
                System.out.println("32323232332");
                break;
            case R.id.sellproduct://上架商品
                sell();
                break;
        }
    }

    private void selectImgs(){

        menuWindow = new SelectPicPopupWindow(getActivity(), itemsOnClick);
        //设置弹窗位置
        menuWindow.showAtLocation(getActivity().findViewById(R.id.ll_image), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.item_popupwindows_camera:        //点击拍照按钮
                    take_photo();
                    break;
                case R.id.item_popupwindows_Photo:       //点击从相册中选择按钮
                    choose_photo();

                    break;
                default:
                    break;
            }
        }

    };

    public void sell(){

        tagsInt.clear();
        int count = 0;

        for (CheckBox checkbox : checkBoxList) {
            if (checkbox.isChecked()){
                tags.add(checkbox.getText().toString());
                count++;
            }
        }
        //is double check
        Pattern pattern = Pattern.compile("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}");

        Matcher isNum = pattern.matcher(sellprice.getText());

        if (count == 0){
            Toast.makeText(getContext(), "请至少选择一个", Toast.LENGTH_SHORT).show();
        }
        else if(!isNum.matches() || selldescribe.getText().equals("") || sellname.getText().equals("")){
            Toast.makeText(getContext(), "invalid info input", Toast.LENGTH_SHORT).show();
        }
        //photo whether empty check
        else if(urls.isEmpty()){
            Toast.makeText(getContext(), "At least one photo", Toast.LENGTH_SHORT).show();
        }
        else{

            for (int i = 0; i < tags.size(); i++) {
                for (int k = 0; k < TagList.size(); k++) {
                    if(tags.get(i).equals(TagList.get(k).getName())){
                        tagsInt.add(TagList.get(k).getTag_id());
                    }
                }
            }

            JSONObject itemJSON = new JSONObject();
            try{
                itemJSON.put("name",sellname.getText().toString());
                itemJSON.put("description",selldescribe.getText().toString());
                itemJSON.put("pre_price",Double.parseDouble(sellprice.getText().toString()));
                itemJSON.put("provider_id", User.getUserId());

                JSONArray likeArray = new JSONArray();
                likeArray.put(tagsInt);
                itemJSON.put("tag_list",likeArray);

                JSONArray urlArray = new JSONArray();
                for (int i = 0; i < urls.size(); i++) {
                    urlArray.put(urls.get(i));
                }
                itemJSON.put("url_list",urlArray);

                JSONArray tagArray = new JSONArray();
                for (int i = 0; i < tagsInt.size(); i++) {
                    tagArray.put(tagsInt.get(i));
                }
                itemJSON.put("tag_list",tagArray);

                String json = itemJSON.toString();
                MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
                RequestBody requestBody = RequestBody.Companion.create(json, mediaType);
                System.out.println("request json is " + json);

                OkHttpUtils.sendOkHttpResponse(LocalData.getInstance().getIp() + "merchandise/create", requestBody, new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        System.out.println(e);
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                        final String data = response.body().string();
                        int state = 2;

                        try {
                            JSONObject stateJson = new JSONObject(data);
                            state = stateJson.getInt("errcode");

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        Looper.prepare();

                        if(state == 2){
                            Toast.makeText(getActivity(), "Upload failed", Toast.LENGTH_SHORT).show();

                        }
                        else if(state == 1){
                            Toast.makeText(getActivity(), "Missing data", Toast.LENGTH_SHORT).show();

                        }
                        else{
                            Toast.makeText(getActivity(), "Upload succeeded", Toast.LENGTH_SHORT).show();
                            //todo 初始化界面
                            handler.sendEmptyMessage(1);
                        }

                        Looper.loop();
                    }
                });
            }catch(JSONException e){
                e.printStackTrace();
            }
        }
    }
}